<template>
  <div class="echarts-wrap">
    <div id="chart-container"></div>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { rawData } from './data'
  export default {
    name: 'Home',
    components: {
    },
    data() {
      return {
        dom: null,
        data: {},
        option: {},
        myChart: null
      }
    },
    computed: {
      ...mapGetters([
      ])
    },
    watch: {
    },
    created() {
      this.data = this.initData()
      console.log('vue==>>created, data: %o, myChart: %o', this.data, !!window.myChart)
    },
    mounted() {
      console.log('vue==>>mounted')
      this.createChart()
      this.updateChart()
    },
    updated(){
      console.log('vue==>>updated')
    },
    destoryed(){
      console.log('vue==>>destoryed')
      if(this.myChart){
        this.myChart.dispose()
      }
    },
    methods: {
      createChart(){
        this.myChart = window.myChart
        if(!this.myChart){
          let dom = document.getElementById("chart-container");
          console.log('vue==>>createChart, echart not init')
          this.myChart = window.echarts.init(dom, null, {
            locale: 'ZH'
          });
          window.myChart = this.myChart
        }
        this.myChart.clear()
        console.log('vue==>>createChart, myChart: %o', this.myChart.id)
        let option = this.initOption(this.data)
        this.myChart.setOption(option, true)
        this.myChart.on('click', {seriesName: '日K'}, function(e){
          console.log(e)
        })
      },
      updateChart(){
        setInterval(()=>{
          let date = '2021-03-08'
          this.data.categoryData.push()

          let open = 17500 + Math.floor(Math.random() * 400)
          let close = 17500 + Math.floor(Math.random() * 400)
          let lowest = 17500 + Math.floor(Math.random() * 400)
          let highest = 17500 + Math.floor(Math.random() * 400)

          let isMore = open >= close ? 1 : -1

          let r = 75000000 + Math.floor(Math.random() * 20000000)
          let volume = [this.data.volumes.length - 1, r, isMore]
          this.data.volumes.push(volume)

          let change = [open, close, lowest, highest]
          this.data.values.push(change)

          let option = this.myChart.getOption()
          option.xAxis[0].data.push(date)
          option.xAxis[1].data.push(date)

          // 日K
          option.series[0].data.push(change)
          //m5,10,20,30
          // option.series[1].data.push(this.calculateMA(5, this.data, this.data.values.length - 1)[0])
          // option.series[2].data.push(this.calculateMA(10, this.data, this.data.values.length - 1)[0])
          // option.series[3].data.push(this.calculateMA(20, this.data, this.data.values.length - 1)[0])
          // option.series[4].data.push(this.calculateMA(30, this.data, this.data.values.length - 1)[0])
          //
          option.series[1].data.push(volume)

          this.myChart.setOption(option)
        }, 2000)
      },
      initData() {
        var categoryData = [];
        var values = [];
        var volumes = [];
        for (var i = 0; i < rawData.length; i++) {
          categoryData.push(rawData[i].splice(0, 1)[0]);
          values.push(rawData[i]);
          volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
        }

        return {
          categoryData: categoryData,
          values: values,
          volumes: volumes
        };
      },
      initOption(data) {
        let calculateMA = this.calculateMA
        var upColor = '#00C977';
        var downColor = '#E6446B';
        return {
          animation: true,
          backgroundColor: '#13141F',
          // legend: {
          //   // bottom: 10,
          //   show: false,
          //   left: 'center',
          //   data: ['日K'], // 'MA5', 'MA10', 'MA20', 'MA30'],
          //   textStyle: {
          //     color: '#fff'
          //   }
          // },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            borderWidth: 1,
            borderColor: '#ccc',
            padding: 10,
            textStyle: {
              color: '#000'
            },
            position: function (pos, params, el, elRect, size) {
              var obj = { top: 10 };
              obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
              return obj;
            }
          },
          axisPointer: { // 指示坐标轴当前刻度的工具
            link: { xAxisIndex: 'all' },
            label: {
              backgroundColor: '#777'
            }
          },
          toolbox: {
            show: false,
            feature: {
              dataZoom: {
                yAxisIndex: false
              },
              brush: {
                type: ['lineX', 'clear']
              }
            }
          },
          brush: {
            xAxisIndex: 'all',
            brushLink: 'all',
            outOfBrush: {
              colorAlpha: 0.1
            }
          },
          visualMap: {
            show: false,
            seriesIndex: 1, //5,
            dimension: 2,
            pieces: [{
              value: 1,
              color: downColor
            }, {
              value: -1,
              color: upColor
            }]
          },
          grid: [
            {
              left: '10%',
              right: '8%',
              top: '25%',
              height: '50%'
            },
            {
              left: '10%',
              right: '8%',
              top: '83%',
              height: '16%'
            }
          ],
          xAxis: [
            {
              type: 'category',
              data: data.categoryData,
              scale: true,
              boundaryGap: false,
              axisLine: { onZero: false },
              splitLine: { show: false },
              splitNumber: 20,
              min: 'dataMin',
              max: 'dataMax',
              axisPointer: {
                z: 100
              }
            },
            {
              type: 'category',
              gridIndex: 1,
              data: data.categoryData,
              scale: true,
              boundaryGap: false,
              axisLine: { onZero: false },
              axisTick: { show: false },
              splitLine: { show: false },
              axisLabel: { show: false },
              splitNumber: 20,
              min: 'dataMin',
              max: 'dataMax'
            }
          ],
          yAxis: [
            {
              scale: true,
              splitLine: false,
              splitArea: {
                show: false
              }
            },
            {
              scale: true,
              gridIndex: 1,
              splitNumber: 2,
              axisLabel: { show: false },
              axisLine: { show: false },
              axisTick: { show: false },
              splitLine: { show: false }
            }
          ],
          dataZoom: [
            {
              type: 'inside',
              xAxisIndex: [0, 1],
              start: 98,
              end: 100
            },
            {
              show: false,
              xAxisIndex: [0, 1],
              type: 'slider',
              top: '85%',
              start: 98,
              end: 100
            }
          ],
          series: [
            {
              name: '日K',
              type: 'candlestick',
              data: data.values,
              itemStyle: {
                color: upColor,
                color0: downColor,
                borderColor: null,
                borderColor0: null
              },
              tooltip: {
                formatter: function (param) {
                  console.log('echarts/index.vue==>> param: %o', param)
                  param = param[0];
                  return [
                    '时间: ' + param.name + '<hr size=1 style="margin: 3px 0">',
                    '开盘: ' + param.data[0] + '<br/>',
                    '收盘: ' + param.data[1] + '<br/>',
                    '最低: ' + param.data[2] + '<br/>',
                    '最高: ' + param.data[3] + '<br/>'
                  ].join('');
                }
              }
            },
            // {
            //   name: 'MA5',
            //   type: 'line',
            //   data: calculateMA(5, data),
            //   smooth: true,
            //   showSymbol: false,
            //   lineStyle: {
            //     width: 1,
            //     opacity: 0
            //   }
            // },
            // {
            //   name: 'MA10',
            //   type: 'line',
            //   data: calculateMA(10, data),
            //   smooth: true,
            //   showSymbol: false,
            //   lineStyle: {
            //     opacity: 0
            //   }
            // },
            // {
            //   name: 'MA20',
            //   type: 'line',
            //   data: calculateMA(20, data),
            //   smooth: true,
            //   showSymbol: false,
            //   lineStyle: {
            //     opacity: 0
            //   }
            // },
            // {
            //   name: 'MA30',
            //   type: 'line',
            //   data: calculateMA(30, data),
            //   smooth: true,
            //   showSymbol: false,
            //   lineStyle: {
            //     opacity: 0
            //   }
            // },
            {
              name: '交易量',
              type: 'bar',
              xAxisIndex: 1,
              yAxisIndex: 1,
              data: data.volumes
            }
          ]
        }
      },
      calculateMA(dayCount, data, idx = 0) {
        var result = [];
        for (var i = idx, len = data.values.length; i < len; i++) {
            if (i < dayCount) {
                result.push('-');
                continue;
            }
            var sum = 0;
            for (var j = 0; j < dayCount; j++) {
                sum += data.values[i - j][1];
            }
            result.push(+(sum / dayCount).toFixed(3));
        }
        return result;
      },
    }
  }
</script>
<style lang="scss" scoped>
  @import "./index.scss";
</style>
